<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card class="search-card" v-show="showSearch">
            <el-form :model="queryParams">
                <el-row :gutter="20">
                    <el-col :span="7">
                        <el-form-item label="通道名称">
                            <el-input v-model="queryParams.messageChannelName" placeholder="请输入通道名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="通道类型">
                            <el-select v-model="queryParams.messageChannelType" placeholder="请选择通道类型" clearable>
                                <el-option label="全部" value="" />
                                <el-option label="短信" :value="0" />
                                <el-option label="邮件" :value="1" />
                                <el-option label="钉钉" :value="2" />
                                <el-option label="企业微信" :value="3" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="启用状态">
                            <el-select v-model="queryParams.isEnabled" placeholder="请选择状态" clearable>
                                <el-option label="全部" value="" />
                                <el-option label="已启用" :value="1" />
                                <el-option label="未启用" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card class="operation-card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="Delete" :disabled="!selectedRows.length"
                        @click="handleBatchDelete">删除</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="channelList" @selection-change="handleSelectionChange"
                style="width: 100%">
                <el-table-column type="selection" width="55" align="center" />
                <!-- <el-table-column prop="messageChannelId" label="通道编号" align="center" /> -->
                <el-table-column type="index" label="序号" width="55" align="center" />

                <el-table-column prop="messageChannelName" label="通道名称" align="center" />
                <el-table-column prop="messageChannelType" label="通道类型" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getTypeTagType(row.messageChannelType)">
                            {{ getTypeName(row.messageChannelType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="isEnabled" label="启用状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.isEnabled === 1 ? 'success' : 'danger'">
                            {{ row.isEnabled === 1 ? '已启用' : '未启用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="configId" label="配置编号" align="center" />
                <!-- <el-table-column label="配置编号" align="center">
                    <template #default="{ row }">
                        {{configList.find((item) => item.id == row.configId)?.name || row.configId}}
                    </template>
                </el-table-column> -->

                <el-table-column label="操作" align="center" width="180">
                    <template #default="{ row }">
                        <el-button type="text" icon="Edit" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="text" icon="Delete" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                    :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleQuery" @current-change="handleQuery" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" @closed="resetForm">
            <el-form ref="channelForm" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="通道编号" prop="messageChannelId" v-if="dialog.isEdit">
                    <el-input v-model="form.messageChannelId" disabled />
                </el-form-item>
                <el-form-item label="通道名称" prop="messageChannelName">
                    <el-input v-model="form.messageChannelName" placeholder="请输入通道名称" />
                </el-form-item>
                <el-form-item label="通道类型" prop="messageChannelType">
                    <el-select v-model="form.messageChannelType" @change="messageChannelTypeSelectChange"
                        placeholder="请选择通道类型">
                        <el-option label="短信" :value="0" />
                        <el-option label="邮件" :value="1" />
                        <el-option label="钉钉" :value="2" />
                        <el-option label="企业微信" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item label="配置" prop="configId">
                    <!-- <el-input-number v-model="form.configId" :min="0" placeholder="请输入配置编号" /> -->
                    <el-select v-model="form.configId" placeholder="请选择配置">
                        <el-option :label="item.name" v-for="item in configList" :key="item.id" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="启用状态" prop="isEnabled">
                    <el-switch v-model="form.isEnabled" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Delete } from '@element-plus/icons-vue'
import {
    listMessageChannel,
    getMessageChannel,
    addMessageChannel,
    updateMessageChannel,
    deleteMessageChannel,
    exportMessageChannel,
    getMessageTypeDictList
} from '@/api/basic/message/passage.js'

const showSearch = ref(true)

// 数据状态
const loading = ref(false)
const channelList = ref([])
const total = ref(0)
const selectedRows = ref([])
const channelForm = ref(null)
const configList = ref([]);
// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    messageChannelName: '',
    messageChannelType: '',
    isEnabled: ''
})

// 表单数据
const form = reactive({
    messageChannelId: undefined,
    messageChannelName: '',
    messageChannelType: '',
    isEnabled: '',
    configId: null
})

// 对话框状态
const dialog = reactive({
    visible: false,
    title: '',
    isEdit: false
})

// 表单验证规则
const rules = reactive({
    messageChannelName: [
        { required: true, message: '请输入通道名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
    ],
    messageChannelType: [
        { required: true, message: '请选择通道类型', trigger: 'change' }
    ],
    configId: [
        { required: true, message: '请选择配置', trigger: 'change' }
    ],
})

// 获取通道类型名称
const getTypeName = (type) => {
    const types = {
        0: '短信',
        1: '邮件',
        2: '钉钉',
        3: '企业微信'
    }
    return types[type] || '未知'
}

// 获取通道类型标签样式
const getTypeTagType = (type) => {
    const types = {
        0: 'primary',
        1: 'success',
        2: 'warning',
        3: 'danger'
    }
    return types[type] || 'info'
}

// 获取消息通道列表
const getList = async () => {
    loading.value = true
    try {
        const res = await listMessageChannel(queryParams)
        channelList.value = res.rows || []
        total.value = res.total || 0
    } catch (error) {
        console.error('获取通道列表失败:', error)
        ElMessage.error('获取通道列表失败')
    } finally {
        loading.value = false
    }
}

// 查询处理
const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
}

// 重置查询
const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.messageChannelName = ''
    queryParams.messageChannelType = ''
    queryParams.isEnabled = ''
    getList()
}

// 多选处理
const handleSelectionChange = (selection) => {
    selectedRows.value = selection.map(item => item.messageChannelId)
}

// 新增通道
const handleAdd = () => {
    dialog.visible = true
    dialog.title = '新增消息通道'
    dialog.isEdit = false
}

// 编辑通道
const handleEdit = async (row) => {
    try {
        const res = await getMessageChannel(row.messageChannelId)
        Object.assign(form, res.data)
        messageChannelTypeSelectChange(res.data.messageChannelType);
        dialog.visible = true
        dialog.title = '编辑消息通道'
        dialog.isEdit = true
    } catch (error) {
        console.error('获取通道详情失败:', error)
        ElMessage.error('获取通道详情失败')
    }
}

// 删除通道
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该消息通道吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteMessageChannel(row.messageChannelId)
            ElMessage.success('删除成功')
            getList()
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => { })
}
const messageChannelTypeSelectChange = (value) => {
    console.log(value);
    getMessageTypeDictList({ typeValue: value }).then((res) => {
        configList.value = res.data;
    })
}

// 批量删除
const handleBatchDelete = () => {
    ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteMessageChannel(selectedRows.value.join(','))
            ElMessage.success('批量删除成功')
            getList()
        } catch (error) {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }).catch(() => { })
}

// 导出Excel
const handleExport = async () => {
    try {
        await exportMessageChannel({
            messageChannelName: queryParams.messageChannelName,
            isDefault: queryParams.isEnabled
        })
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 重置表单
const resetForm = () => {
    if (channelForm.value) {
        channelForm.value.resetFields()
    }
    Object.assign(form, {
        messageChannelId: undefined,
        messageChannelName: '',
        messageChannelType: '',
        isEnabled: '',
        configId: ''
    })
}

// 提交表单
const submitForm = async () => {
    try {
        await channelForm.value.validate()

        if (dialog.isEdit) {
            await updateMessageChannel(form)
            ElMessage.success('修改成功')
        } else {
            await addMessageChannel(form)
            ElMessage.success('新增成功')
        }
        dialog.visible = false
        getList()
    } catch (error) {
        if (error && error.fields) {
            ElMessage.warning('请检查表单填写是否正确')
        } else {
            console.error('操作失败:', error)
            ElMessage.error('操作失败')
        }
    }
}

// 初始化
onMounted(() => {
    getList()
})
</script>

<style scoped>
.search-card {
    margin-bottom: 20px;
}

.search-buttons {
    text-align: right;
    padding-top: 5px;
}

.operation-card {
    margin-bottom: 20px;
}

.operation-buttons {
    display: flex;
    gap: 10px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.search-card :deep(.el-form-item) {
    margin-bottom: 0px;
}
</style>